﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 产品料号服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class PartnumService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Partnum> _partnumRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly SysDictTypeService _sysDictTypeService;

    public PartnumService(SqlSugarRepository<Partnum> partnumRep, ISqlSugarClient sqlSugarClient, SysDictTypeService sysDictTypeService)
    {
        _partnumRep = partnumRep;
        _sqlSugarClient = sqlSugarClient;
        _sysDictTypeService = sysDictTypeService;
    }

    /// <summary>
    /// 分页查询产品料号 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询产品料号")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<PartnumOutput>> Page(PagePartnumInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _partnumRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.PartNumCoding.Contains(input.Keyword) || u.PartNumName.Contains(input.Keyword) || u.SpeciFicationNumber.Contains(input.Keyword) || u.PartNumUnit.Contains(input.Keyword) || u.PartNumPreWarning.Contains(input.Keyword) || u.PartNumType.Contains(input.Keyword) || u.PartNumDescribe.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PartNumCoding), u => u.PartNumCoding.Contains(input.PartNumCoding.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PartNumName), u => u.PartNumName.Contains(input.PartNumName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SpeciFicationNumber), u => u.SpeciFicationNumber.Contains(input.SpeciFicationNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PartNumUnit), u => u.PartNumUnit.Contains(input.PartNumUnit.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PartNumPreWarning), u => u.PartNumPreWarning.Contains(input.PartNumPreWarning.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PartNumType), u => u.PartNumType.Contains(input.PartNumType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PartNumDescribe), u => u.PartNumDescribe.Contains(input.PartNumDescribe.Trim()))
            .WhereIF(input.MasterDataId != null, u => u.MasterDataId == input.MasterDataId)
            .LeftJoin<Master>((u, masterData) => u.MasterDataId == masterData.Id)
            .Select((u, masterData) => new PartnumOutput
            {
                Id = u.Id,
                PartNumCoding = u.PartNumCoding,
                PartNumName = u.PartNumName,
                SpeciFicationNumber = u.SpeciFicationNumber,
                PartNumUnit = u.PartNumUnit,
                PartNumPreWarning = u.PartNumPreWarning,
                PartNumType = u.PartNumType,
                MasterDataId = u.MasterDataId,
                MasterDataFkDisplayName = $"{masterData.MasterName}",
                PartNumDescribe = u.PartNumDescribe,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取产品料号详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取产品料号详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Partnum> Detail([FromQuery] QueryByIdPartnumInput input)
    {
        return await _partnumRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加产品料号 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加产品料号")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddPartnumInput input)
    {
        var entity = input.Adapt<Partnum>();
        return await _partnumRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新产品料号 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新产品料号")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdatePartnumInput input)
    {
        var entity = input.Adapt<Partnum>();
        await _partnumRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除产品料号 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除产品料号")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeletePartnumInput input)
    {
        var entity = await _partnumRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _partnumRep.FakeDeleteAsync(entity);   //假删除
        //await _partnumRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除产品料号 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除产品料号")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeletePartnumInput> input)
    {
        var exp = Expressionable.Create<Partnum>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _partnumRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _partnumRep.FakeDeleteAsync(list);   //假删除
        //return await _partnumRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataPartnumInput input)
    {
        var masterDataIdData = await _partnumRep.Context.Queryable<Master>()
            .InnerJoinIF<Partnum>(input.FromPage, (u, r) => u.Id == r.MasterDataId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.MasterName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "masterDataId", masterDataIdData },
        };
    }
    
    /// <summary>
    /// 导出产品料号记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出产品料号记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PagePartnumInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportPartnumOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        var partNumUnitDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "Unit-of-product-part-number" }).Result.ToDictionary(x => x.Value, x => x.Label);
        var partNumTypeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "Dictionary-of-the-main-data-group-type" }).Result.ToDictionary(x => x.Value, x => x.Label);
        list.ForEach(e => {
            e.PartNumUnitDictLabel = partNumUnitDictMap.GetValueOrDefault(e.PartNumUnit ?? "", e.PartNumUnit);
            e.PartNumTypeDictLabel = partNumTypeDictMap.GetValueOrDefault(e.PartNumType ?? "", e.PartNumType);
        });
        return ExcelHelper.ExportTemplate(list, "产品料号导出记录");
    }
    
    /// <summary>
    /// 下载产品料号数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载产品料号数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportPartnumOutput>(), "产品料号导入模板", (_, info) =>
        {
            if (nameof(ExportPartnumOutput.MasterDataFkDisplayName) == info.Name) return _partnumRep.Context.Queryable<Master>().Select(u => $"{u.MasterName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入产品料号记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入产品料号记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var partNumUnitDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "Unit-of-product-part-number" }).Result.ToDictionary(x => x.Label!, x => x.Value);
            var partNumTypeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "Dictionary-of-the-main-data-group-type" }).Result.ToDictionary(x => x.Label!, x => x.Value);
            var stream = ExcelHelper.ImportData<ImportPartnumInput, Partnum>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 群组
                    var masterDataIdLabelList = pageItems.Where(x => x.MasterDataFkDisplayName != null).Select(x => x.MasterDataFkDisplayName).Distinct().ToList();
                    if (masterDataIdLabelList.Any()) {
                        var masterDataIdLinkMap = _partnumRep.Context.Queryable<Master>().Where(u => masterDataIdLabelList.Contains($"{u.MasterName}")).ToList().ToDictionary(u => $"{u.MasterName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.MasterDataId = masterDataIdLinkMap.GetValueOrDefault(e.MasterDataFkDisplayName ?? "");
                            if (e.MasterDataId == null) e.Error = "群组链接失败";
                        });
                    }
                    
                    // 映射字典值
                    foreach(var item in pageItems) {
                        if (string.IsNullOrWhiteSpace(item.PartNumUnitDictLabel)) continue;
                        item.PartNumUnit = partNumUnitDictMap.GetValueOrDefault(item.PartNumUnitDictLabel);
                        if (item.PartNumUnit == null) item.Error = "单位字典映射失败";
                        if (string.IsNullOrWhiteSpace(item.PartNumTypeDictLabel)) continue;
                        item.PartNumType = partNumTypeDictMap.GetValueOrDefault(item.PartNumTypeDictLabel);
                        if (item.PartNumType == null) item.Error = "群组类型字典映射失败";
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Partnum>>();
                    
                    var storageable = _partnumRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.PartNumCoding?.Length > 32, "产品编码长度不能超过32个字符")
                        .SplitError(it => it.Item.PartNumName?.Length > 32, "产品名称长度不能超过32个字符")
                        .SplitError(it => it.Item.SpeciFicationNumber?.Length > 32, "规格型号长度不能超过32个字符")
                        .SplitError(it => it.Item.PartNumUnit?.Length > 32, "单位长度不能超过32个字符")
                        .SplitError(it => it.Item.PartNumPreWarning?.Length > 32, "预警值长度不能超过32个字符")
                        .SplitError(it => it.Item.PartNumType?.Length > 32, "群组类型长度不能超过32个字符")
                        .SplitError(it => it.Item.PartNumDescribe?.Length > 32, "产品描述长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
